package com.jn.algorithm.day016.question46;

import java.util.*;

/**
 * @author 江南大学1033190417
 * @date 2022/5/8 0:59
 */
public class Solution {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();

        List<Integer> output = new ArrayList<Integer>();
        for (int num : nums) {
            output.add(num);
        }

        int n = nums.length;
        backtrack(n, output, res, 0);
        return res;
    }

    public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
        // 所有数都填完了
        if (first == n) {
            res.add(new ArrayList<Integer>(output));
        }
        for (int i = first; i < n; i++) {
            // 动态维护数组
            Collections.swap(output, first, i);
            // 继续递归填下一个数
            backtrack(n, output, res, first + 1);
            // 撤销操作
            Collections.swap(output, first, i);
        }
    }

    //自己写
    public List<List<Integer>> myPermute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        int length = nums.length;
        List<Integer> output = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            output.add(nums[i]);
        }
        Deque<Integer> path = new ArrayDeque<>();
        boolean[] used = new boolean[length];
        dfs(used, 0, length, nums, res, path);
        return res;
    }

    public void dfs(boolean[] used, int depth, int len, int[] nums, List<List<Integer>> res, Deque<Integer> path) {
        if (depth == len) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < len; i++) {
            if (used[i]) {
                continue;
            }
            path.addLast(nums[i]);
            used[i] = true;
            dfs(used, depth + 1, len, nums, res, path);
            path.removeLast();
            used[i] = false;
        }
    }


    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = new int[]{1, 2, 3};
        System.out.println(solution.myPermute(nums));
    }
}
